
# Set working directory
setwd("C:/Users/daviv/Documents/Davi/Mestrado DCP/Paper payouts/Updates_19_02") # adjust to your computer

# Load packages
library(tidyverse)
library(tidylog)
library(ggplot2)
library(haven)
library(gridExtra)

# Load data
ddr <- read_dta("ddrclacomparedmerged.dta")

# Rename Dominican Republic to improve visualization
ddr <- ddr %>%
  mutate(
    ctryname =
      case_when(ctryname == "Dominican Republic" ~ "Dominican R.",
                TRUE ~ ctryname
      )
  )

# Prepare data
country_data <- ddr %>%
  select(ctryname, year, democracyddrla, democracylied, bmr_democracy, 
         vdem_democracy, democracy_mpl, polity2v_democracy, brdemocracy,
         dd_democracy) %>%
  pivot_longer(cols = c(democracyddrla, democracylied, bmr_democracy, vdem_democracy, 
                        democracy_mpl, polity2v_democracy, brdemocracy, dd_democracy),
               names_to = "democracy_variable",
               values_to = "democracy_value") %>%
  mutate(democracy_variable = case_when(
    democracy_variable == "democracyddrla" ~ "DDRLA",
    democracy_variable == "democracylied" ~ "LIED",
    democracy_variable == "bmr_democracy" ~ "BMR",
    democracy_variable == "democracy_mpl" ~ "MPL",
    democracy_variable == "polity2v_democracy" ~ "Polity",
    democracy_variable == "vdem_democracy" ~ "V-DEM",
    democracy_variable == "brdemocracy" ~ "BR",
    democracy_variable == "dd_democracy" ~ "DD",
    TRUE ~ ""
  )) %>% 
  select(ctryname, year, democracy_variable, democracy_value)

# Plot regime type comparison

# Loop over each unique country name
unique_countries <- unique(ddr$ctryname)

# Create empty list to store plots
plots_list <- list()  

for (country_name in unique_countries) {
  # Plot for each country
  plot_country <- country_data %>%
    filter(ctryname == country_name) %>%
    mutate(democracy_value = as.factor(democracy_value)) %>% 
    filter(!is.na(democracy_value)) %>% 
    ggplot(aes(x=year, y=democracy_variable)) +
    geom_tile(aes(fill=democracy_value), col="black") +
    scale_fill_manual(values=c("grey42", "grey20")) +
    labs(x="Year",y="Coding Rule", title=paste("Regime Type in", country_name)) +
    theme(plot.title = element_text(hjust = 0.5))+
    guides(fill=guide_legend(title="Value"))+ theme_bw() + 
    theme(panel.border = element_blank(), panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(), axis.line = 
            element_line(colour = "black"))
  
  # Store the plots in the list
  plots_list[[country_name]] <- plot_country
}

# Plot
grid.arrange(grobs = plots_list)

# Save plot
plot <- grid.arrange(grobs = plots_list)

ggsave("regime_type_comparison_plot.png", plot, width = 14, height = 8, 
       units = "in", dpi = 600)

